#include "searchresultlist.h"
#include <QEvent>
#include <QJsonDocument>
#include <QLineEdit>
#include <QPainter>
#include <QScrollBar>
#include <QStyleOption>
#include <QWheelEvent>
#include "findfaildlg.h"
#include "findsuccessdlg.h"
#include "tcpmgr.h"
SearchResultList::SearchResultList(QWidget *parent)
    : QListWidget(parent)
    , _sendSpending(false)
    , _findDlg(nullptr)
    , _searchEdit(nullptr)
    , _loadingDlg(nullptr)
{
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    this->verticalScrollBar()->setVisible(false);
    this->viewport()->installEventFilter(this);
    // 项被点击
    connect(this, &QListWidget::itemClicked, this, &SearchResultList::slot_itemClicked);
    // 模拟添加数据
    addTipItem();
    // 网络请求结果
    connect(TcpMgr::GetInstance().get(),
            &TcpMgr::sig_user_search,
            this,
            &SearchResultList::slot_userSearch);
}

void SearchResultList::setSearchEdit(QWidget *edit)
{
    _searchEdit = edit;
}

bool SearchResultList::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == this->viewport()) {
        if (event->type() == QEvent::Enter) {
            this->verticalScrollBar()->setVisible(true);
        }
        if (event->type() == QEvent::Leave) {
            this->verticalScrollBar()->setVisible(false);
        }
        if (event->type() == QEvent::Wheel) {
            QWheelEvent *we = dynamic_cast<QWheelEvent *>(event);
            int numDegress = we->angleDelta().y() / 8;
            int numSteps = numDegress / 15;
            // 设置滚动幅度
            this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() - numSteps);
        }
        return QListWidget::eventFilter(watched, event);
    }
    return QListWidget::eventFilter(watched, event);
}

void SearchResultList::slot_RedPointVisible(bool visible)
{
    _addUserItem->setRedPointVisible(visible);
    _addUserItem->update();
}

void SearchResultList::waitPending(bool pending)
{
    if (pending) {
        _loadingDlg = new LoadingDlg(this);
        _loadingDlg->setModal(true);
        _loadingDlg->show();
        _sendSpending = pending;
    } else {
        _loadingDlg->hide();
        _loadingDlg->deleteLater();
        _sendSpending = pending;
    }
}

void SearchResultList::addTipItem()
{
    _addUserItem = new AddUserItem(this);
    QListWidgetItem *item = new QListWidgetItem();
    _addUserItem->setObjectName("add_user_item");
    item->setSizeHint(_addUserItem->sizeHint());
    item->setFlags(Qt::NoItemFlags);
    this->addItem(item);
    this->setItemWidget(item, _addUserItem);
}

void SearchResultList::slot_itemClicked(QListWidgetItem *item)
{
    QWidget *w = this->itemWidget(item);
    if (!w) {
        qDebug() << "slot item clicked widget is null";
        return;
    }
    BaseItem *customItem = static_cast<BaseItem *>(w);
    if (!customItem) {
        qDebug() << "slot item clicked Item is null";
        return;
    }
    auto itemType = customItem->GetItemType();
    if (itemType == BaseItem::ADD_USER_TIP_ITEM) {
        // 处于发送状态
        if (!_searchEdit) {
            return;
        }
        if (_sendSpending) {
            return;
        }
        waitPending(true);
        QLineEdit *lineEdit = dynamic_cast<QLineEdit *>(_searchEdit);
        QString uid_str = lineEdit->text().trimmed();
        QJsonObject jsonObj;
        jsonObj["uid"] = uid_str;
        QJsonDocument doc(jsonObj);
        QByteArray jsonData = doc.toJson(QJsonDocument::Compact);
        // 发送搜索好友请求
        emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_SEARCH_USER_REQ, jsonData);
        return;
    }
    // closeDlg();
}

void SearchResultList::slot_userSearch(std::shared_ptr<SearchInfo> si)
{
    //停止等待
    waitPending(false);
    // 空指针 返回结果出现错误 查找失败对话框
    if (si == nullptr) {
        _findDlg = std::make_shared<FindFailDlg>(this);
    } else {
        // 搜索到的用户可能是已添加好友
        _findDlg = std::make_shared<FindSuccessDlg>(this);
        auto findSuccessDlg = std::dynamic_pointer_cast<FindSuccessDlg>(_findDlg);
        findSuccessDlg->setSearchInfo(si);
    }
    _findDlg->show();
}

void SearchResultList::paintEvent(QPaintEvent *event)
{
    // 创建一个QStyleOption对象
    QStyleOption opt;
    opt.initFrom(this->viewport());
    // 创建一个QPainter对象，用于绘制
    QPainter p(this->viewport());
    // 使用样式表绘制控件
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    // 调用父类的paintEvent方法，处理其他绘制事件
    QListWidget::paintEvent(event);
}
